const router = require('koa-router')() // 一边导入一边实例化
// const result = require('../../config/result.js')
// const { regcheck, checking } = require('../../config/checking.js')
const fs = require('fs');
const axios = require('axios');
// 操作数据库的接口
const { getToken, DownloadFileUrl } = require('../../config/databaseapi.js');
const { PassThrough } = require('stream');
// 注册接口
router.post('/multipledownload', async (ctx) => {
  console.log('调用批量下载文件接口');
  // console.log(ctx.request.body);
  let { file_list, file_name } = ctx.request.body;
  let res1 = await new getToken().posteve4(DownloadFileUrl, file_list);
  // console.log(res1);
  if (res1.errcode === 0) {
    let data = [];
    for (let i = 0; i < res1.file_list.length; i++) {
      // console.log(res1.file_list[i]);
      let fileName = '';
      let type = '';
      for (let j = 0; j < file_name.length; j++) {
        if (file_name[j].fileid === res1.file_list[i].fileid) {
          fileName = file_name[j].fileName;
          type = file_name[j].type;
          break;
        }
      }
      const fileUrl = res1.file_list[i].download_url;
      console.log(fileUrl, fileName, type);
      try {
        const response = await axios.get(fileUrl, { responseType: 'stream' });
        const fileStream = new PassThrough();
        response.data.pipe(fileStream);
        data.push({ fileName, fileStream, type });
      } catch (err) {
        // ctx.body = { msg: '接收下载地址成功,下载失败', status: 0 }
        console.log(err);
      }
    }
    // console.log(data.length);
    ctx.body = { msg: '下载成功', status: 1, data }
  } else {
    ctx.body = { msg: '获取下载地址失败', status: 0 }
  }
});

module.exports = router.routes()